<?php

namespace App\Common\Traits\Admin;

use EasySwoole\ORM\DbManager;
use EasySwoole\Template\Render;

use App\Common\Tools;

/**
 * @description: 后台数据列表
 */
trait Lists
{
    /**
     * @description: 列表
     * @param {*}
     * @return {*}
     */
    public function index()
    {
        $param = $this->request()->getRequestParam() ?: $this->indexDeafultParam();
        $data = DbManager::getInstance()->invoke(function ($client) use ($param) {
            $page  = $param['page'] ?? 1;
            $limit = 15;
            $model = $this->model::invoke($client);
            $where = $this->indexWhere($param);
            list($list, $total) = $model->adminPages($page, $limit, $where);
            return Tools::page($page, $list, $total, $limit, $param);
        });
        $class_name = explode('\\' , static::class);
        $template   = '/Admin/' . end($class_name) .'/index';
        $assign = $this->indexAssign();
        $assign['data']  = $data;
        $assign['param'] = $param;
        $assign['url']   = '/admin/' . strtolower(end($class_name)) .'/index.html';
        $this->response()->write(Render::getInstance()->render($template, $assign));
    }

    /**
     * @description: 列表查询条件构建
     * @param array $param 前端参数
     * @return {*}
     */
    protected function indexWhere(array $param)
    {
        return [];
    }

    /**
     * @description: 列表数据额外返回数据
     * @param {*}
     * @return {*}
     */
    protected function indexAssign()
    {
        return [];
    }

    /**
     * @description: 列表查询条件默认字段
     * @param {*}
     * @return {*}
     */
    protected function indexDeafultParam()
    {
        return [];
    }
}